﻿using System;
using System.Net;
using System.IO;
using System.Text;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using DoNet.Utils;

namespace DoNet.TenPay
{
    public class ResponseHandlerV2
    {
        /// <summary>
        /// 请求URL
        /// </summary>
        public string RequestUrl = "";
        /// <summary>
        /// 应答主体（response Body）
        /// </summary>
        public string ResponseBody = "";

        /// <summary>
        /// 获取请求结果
        /// </summary>
        /// <param name="url">微信的接口地址</param>
        /// <param name="merchantId">发起请求的商户（包括直连商户、服务商或渠道商）的商户号 mchid</param>
        /// <param name="method">默认为GET，请求方式 GET、POST</param>
        /// <param name="postData">默认为空，POST/PUT请求的数据，xml格式 GET时 置为空</param>
        /// <param name="isCert">是否使用 API证书 默认false</param>
        /// <param name="contentType">发送端（客户端|服务器）发送的实体数据的数据类型。</param>
        /// <param name="encoding"></param>
        /// <param name="timeout">默认为6秒，请求多少秒超时</param>
        public ResponseHandlerV2(string url, string merchantId, string method = "GET", string postData = null, bool isCert = false, string contentType = null, Encoding encoding = null, int timeout = 6)
        {
            GC.Collect();

            this.RequestUrl = url;

            HttpWebRequest request = null;

            //请求url以获取数据
            try
            {
                //设置最大连接数
                ServicePointManager.DefaultConnectionLimit = 200;
                //设置https验证方式
                if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
                {
                    ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                }

                string USER_AGENT = string.Format("WXPaySDK/{3} ({0}) .net/{1} {2}", Environment.OSVersion, Environment.Version, merchantId, this.GetType().Assembly.GetName().Version);
                request = (HttpWebRequest)WebRequest.Create(url);
                request.UserAgent = USER_AGENT;
                method = method.ToUpper();
                request.Method = method;
                request.Timeout = timeout * 1000;

                if (encoding == null)
                {
                    encoding = Encoding.UTF8; //默认编码
                }

                if (method == "POST")
                {
                    //设置POST的数据类型
                    if (string.IsNullOrEmpty(contentType))
                    {
                        contentType = "text/xml"; //默认为json
                    }
                    request.ContentType = contentType;

                    if (postData != null)
                    {
                        //设置POST的数据类型和长度
                        byte[] data = Encoding.UTF8.GetBytes(postData);
                        request.ContentLength = data.Length;

                        //往服务器写入数据
                        using (Stream reqStream = request.GetRequestStream())
                        {
                            reqStream.Write(data, 0, data.Length);
                            reqStream.Close();
                        }
                    }
                }

                //是否使用证书
                if (isCert)
                {
                    string path = Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory) + Path.DirectorySeparatorChar + "uplaod" + Path.DirectorySeparatorChar + "cert" + Path.DirectorySeparatorChar + merchantId + Path.DirectorySeparatorChar + "apiclient_cert.p12";
                    //Log.Error("WxPayApi", "certPath:" + path + certModel.CertFile);
                    X509Certificate2 cert = new X509Certificate2(path, merchantId);
                    request.ClientCertificates.Add(cert);
                    Log.Debug("WxPayApi", "PostXml used cert");
                }

                //获取服务器返回
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                { //获取HTTP返回数据
                    using (Stream stream = response.GetResponseStream())
                    {
                        using (StreamReader reader = new StreamReader(stream, encoding))
                        {
                            this.ResponseBody = reader.ReadToEnd().Trim();
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Log.Error(this.GetType().Name, e.ToString());
                //throw new WxPayException(e.ToString());
                //Log.Error("ResponseHandler", "RequestUrl：" + this.RequestUrl);
            }
            finally
            {
                //关闭连接和流
                if (request != null)
                {
                    request.Abort();
                }
            }
        }

        public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            //直接确认，否则打不开    
            return true;
        }
    }
}
